const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const admin = require('../middleware/admin');

router.get('/', async (req,res) => {
    try {
        const queryObj = req.query;
        const numberOfItems = 20;   // 每页可显示的数量
        let rateString = '',
            pagingString = '';
        if (queryObj.rate){      // 如果需要分别显示不同评价
            if (queryObj.rate == 'p'){
                rateString = 'AND comments.rate=1';
            }else{
                rateString = 'AND comments.rate=0';
            }
        }
    
        if (queryObj.page){         // 如果需要翻页
            const offset = (parseInt(queryObj.page) - 1) * numberOfItems;
            pagingString = `LIMIT ${offset},${numberOfItems}`;
        }else{
            pagingString = `LIMIT 0,${numberOfItems}`;
        }


        const db = req.app.get('db');
        let queryString = `
            SELECT comments.id, comments.rate, comments.content,
                comments.location, 
                datetime(comments.createDateTime) as cmtCDT, 
                users.nickname as username
            FROM comments
            LEFT JOIN users
            ON comments.userId=users.id
            WHERE comments.isDisabled=0
                ${rateString}
            ORDER BY datetime(comments.createDateTime) DESC
            ${pagingString}
        `;
        const comments = await db.all(queryString);
        res.send({'comments':comments});
    } catch (err) {
        return res.status(500).send({'message':err.message});
    }
});

router.delete('/:id',[auth,admin],async (req,res)=>{
    try {
        const db = req.app.get('db');
        const result = await isExistingComment(req,res);
        if (!result) return;
        await db.run('UPDATE comments SET isDisabled=? WHERE id=?',1,
            parseInt(req.params.id));
        const comment = await db.get('Select * from comments Where isDisabled = 1 AND id=?;', 
            parseInt(req.params.id));
        res.send({'comment':comment,'message':'comment deleted'});
    } catch (err) {
        return res.status(500).send({'message':err.message});
    }
});

async function isExistingComment(req,res){
    const db = req.app.get('db');
    let comment = await db.get('Select * from comments Where isDisabled = 0 AND id=?;',
        parseInt(req.params.id));
    if (!comment) {
        res.status(404).send({'message':'cannot find the comment with the id'});
        return false;
    }
    return comment;
}

module.exports = router;